import { reqUserLogin, reqUserLogout } from '@/api';

const state = {
  userInfo: {
    name: localStorage.getItem('userName'),
    token: localStorage.getItem('token'),
  },
};
const actions = {
  // 1、用户登录
  async userLogin({ commit }, obj) {
    const result = await reqUserLogin(obj);
    if (result.code === 200) {
      commit('SAVE_USER_INFO', result.data);
      // 存到本地存储当中一份
      localStorage.setItem('userName', result.data.name);
      localStorage.setItem('token', result.data.token);
    } else {
      console.log(result.message);
    }
  },
  // 2、用户登出
  async userLogout({ commit }) {
    const result = await reqUserLogout();
    if (result.code === 200) {
      localStorage.removeItem('userName');
      localStorage.removeItem('token');
      commit('REMOVE_USER_INFO');
    }
  },
};
const mutations = {
  // 1、保存用户数据
  SAVE_USER_INFO(state, payload) {
    state.userInfo.name = payload.name; // 是个对象
    state.userInfo.token = payload.token;
  },
  // 2、清除用户数据
  REMOVE_USER_INFO(state) {
    state.userInfo.name = '';
    state.userInfo.token = '';
  },
};
const getters = {};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};
